package com.coolingme.deep;

import lombok.Data;

import java.io.*;
import java.util.List;

/**
 * 深克隆
 * <p>
 * 通过序列化实现深克隆
 *
 * @author wangyue
 * @date 2020/9/30 9:32
 */
@Data
public class ConcretePrototype implements Cloneable, Serializable {

    private String name;

    private Integer age;

    private List<String> hobbies;

    @Override
    public ConcretePrototype clone() {
        try {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(bos);
            oos.writeObject(this);

            ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
            ObjectInputStream ois = new ObjectInputStream(bis);
            ConcretePrototype clone = (ConcretePrototype) ois.readObject();
            return clone;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
